package com.huayi.website.controller;

import com.huayi.website.entity.EnumLanguage;
import com.huayi.website.entity.EnumPages;
import com.huayi.website.entity.NewsEntity;
import com.huayi.website.service.*;
import com.huayi.website.utils.PagingResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class HomeController {
    @Autowired
    private BannerService bannerService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PageContentService pageContentService;
    @Autowired
    private PagesService pagesService;
    @Autowired
    private NewsService newsService;

    @RequestMapping("/")
    public String home(HttpServletRequest request, Model model){
        return "redirect:/en";
    }

    @RequestMapping("/{language}")
    public String home(HttpServletRequest request, Model model, @PathVariable String language) {
        EnumLanguage languageEnum = EnumLanguage.getEnum(language);
        model.addAttribute("language",language);


        var banners = bannerService.getAllList(EnumPages.Home);
        model.addAttribute("banners", banners);

        var products = productService.getAllList(1, 10, "", null, null);
        model.addAttribute("products", products.getList());

        var pageContent = pageContentService.getByPageIdAndLanguage(EnumPages.Home.getIndex(), languageEnum);
        model.addAttribute("pc", pageContent);


        model.addAttribute("menuId", "home");


        PagingResponse<NewsEntity> result =  newsService.getAllList(1,3,null,1,languageEnum.getIndex());

        model.addAttribute("newsList", result.getList());

        //获取页面信息，设置title
        var page = pagesService.getById(EnumPages.Home);
        if (languageEnum == EnumLanguage.CHINESE) {
            model.addAttribute("layout", "layout_zh");
            model.addAttribute("pageTitle", page.getTitleCn());
        }
        else {
            model.addAttribute("pageTitle", page.getTitleEn());
            model.addAttribute("layout", "layout");
        }

        return "home";
    }
}
